﻿//
// Copyright © MixModes Inc. 2011
//

using System;
using System.Windows.Input;
using MixModes.Phone.Synergy.Utilities;

namespace MixModes.Phone.Synergy.Commands
{
    /// <summary>
    /// ICommand implementation
    /// </summary>
    public class CommandBase : ICommand
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="CommandBase"/> class.
        /// </summary>
        /// <param name="execute">The execute action</param>
        public CommandBase(Action<object> execute)
            : this(execute, null)
        {            
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CommandBase"/> class.
        /// </summary>
        /// <param name="execute">The execute action</param>
        /// <param name="canExecute">The execute predicate</param>
        public CommandBase(Action<object> execute, Predicate<object> canExecute)
        {
            Validate.NotNull(execute, "execute");
            ExecuteAction = execute;
            CanExecutePredicate = canExecute;
        }

        /// <summary>
        /// Occurs when changes occur that affect whether the command should execute.
        /// </summary>
        public event EventHandler CanExecuteChanged;

        /// <summary>
        /// Defines the method that determines whether the command can execute in its current state.
        /// </summary>
        /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
        /// <returns>
        /// true if this command can be executed; otherwise, false.
        /// </returns>
        public bool CanExecute(object parameter)
        {
            return CanExecutePredicate != null ? CanExecutePredicate(parameter) : true;
        }

        /// <summary>
        /// Defines the method to be called when the command is invoked.
        /// </summary>
        /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
        public void Execute(object parameter)
        {
            ExecuteAction(parameter);
        }

        /// <summary>
        /// Gets or sets the execute action.
        /// </summary>
        /// <value>The execute action.</value>
        private Action<object> ExecuteAction { get; set; }

        /// <summary>
        /// Gets or sets the can execute predicate.
        /// </summary>
        /// <value>The can execute predicate.</value>
        private Predicate<object> CanExecutePredicate { get; set; }
    }
}
